package com.cloud.log.autolevel.service.impl;


import com.cloud.log.autolevel.bean.LoggerConfig;
import com.cloud.log.autolevel.manager.ZkManager;
import com.cloud.log.autolevel.service.ConfigChangeService;
import com.cloud.log.autolevel.service.LogLevelSettingService;
import com.cloud.log.autolevel.util.GsonUtil;
import com.google.common.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author ZhangKaiQiang
 */
public class ZkConfigChangeServiceImpl implements ConfigChangeService {

    private ZkManager zkManager;

    private LogLevelSettingService logLevelSettingService;

    private Logger logger= LoggerFactory.getLogger(ZkConfigChangeServiceImpl.class);

   public ZkConfigChangeServiceImpl(
           ZkManager zkManager,
           LogLevelSettingService logLevelSettingService){
        this.zkManager=zkManager;
        this.logLevelSettingService=logLevelSettingService;
        this.init();
    }

    @Override
    public void init() {
        logger.info("项目启动,初始化日志配置");

        boolean ifExists = zkManager.checkIfExists(zkManager.getNamespace());
        if (!ifExists){
            logger.info("初始化项目时,不存在项目配置文件路径,path:{}",zkManager.getNamespace());
            return;
        }

        byte[] nodeData = zkManager.getNodeData(zkManager.getNamespace());
        if (nodeData.length<=0){
            logger.info("path:{},节点下数据为空,不需要初始化日志配置",zkManager.getNamespace());
            return;
        }

        String dataStr=new String(nodeData);
        List<LoggerConfig> loggerConfigList = GsonUtil.toList(dataStr, new TypeToken<List<LoggerConfig>>() {});
        if (loggerConfigList!=null && loggerConfigList.size()>0){
            logLevelSettingService.setLoggerLevel(loggerConfigList);
        }

        logger.info("初始化项目日志界别完成");

        this.listenConfigChange();
   }


    @Override
    public void listenConfigChange() {
       logger.info("开启监听节点数据");
       zkManager.createNodeCacheWatch(zkManager.getNamespace(),(data)->{
            byte[] afterChangeData = data.getData();
            String afterChangeStr=new String(afterChangeData);
            List<LoggerConfig> autoLevelConfigList= GsonUtil.toList(afterChangeStr, new TypeToken<List<LoggerConfig>>(){});
            if (autoLevelConfigList!=null && autoLevelConfigList.size()>0){
                logLevelSettingService.setLoggerLevel(autoLevelConfigList);
                logger.info("监听到节点数据变化,更新日志界别完成");
            }
       });
    }
}
